package com.itsu.app.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itsu.app.config.HuanXinConfig;
import com.itsu.app.exception.MyException;
import com.itsu.app.interceptor.UserThreadLocal;
import com.itsu.interfaces.entity.Announcement;
import com.itsu.interfaces.entity.Comment;
import com.itsu.interfaces.entity.UserInfoEntity;
import com.itsu.interfaces.entity.Users;
import com.itsu.pojo.enums.ResultCode;
import com.itsu.pojo.results.ErrorResult;
import com.itsu.pojo.vo.AnnouncementVo;
import com.itsu.pojo.vo.PageResult;
import com.itsu.pojo.vo.UserInfoVo;
import com.itsu.pojo.vo.UsersVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AppIMService {

    @Autowired
    AppUserInfoService appUserInfoService;

    @Autowired
    AppUsersService appUsersService;

    @Autowired
    AppCommentService appCommentService;

    @Autowired
    AppAnnouncementService announcementService;

    @Autowired
    RequestService requestService;

    @Autowired
    HuanXinConfig huanXinConfig;


    public UserInfoVo queryUserInfoByUserId(String userId) {
        UserInfoEntity entity = appUserInfoService.findUserByUid(Convert.toLong(userId));

        UserInfoVo vo = new UserInfoVo();

        vo.setId(entity.getUserId());
        vo.setAvatar(entity.getLogo());
        vo.setNickname(entity.getNickName());
        vo.setBirthday(entity.getBirthday());
        vo.setAge(entity.getAge().toString());
        vo.setGender(entity.getSex() == 2 ? "man" : "woman");
        vo.setCity(entity.getCity());
        vo.setEducation(entity.getEdu());
        vo.setIncome(entity.getIncome());
        vo.setProfession(entity.getIndustry());
        vo.setMarriage("已婚".equals(entity.getMarriage()) ? 1 : 0 );
        return vo;
    }

    public void contacts(Integer userId) {
        String myselfName = "HX_" + UserThreadLocal.getUid();
        String huanxinName = "HX_" + userId;

        HttpResponse response = requestService.execute(huanXinConfig.getUrl() + huanXinConfig.getOrgName()
                        + "/" + huanXinConfig.getAppName() + "/users/" + myselfName + "/contacts/users/" + huanxinName
                , null
                , Method.POST);

        if (!response.isOk()) {
            throw new MyException(new ErrorResult(ResultCode.USER_REGIT_ERROR));
        }


        appUsersService.addUsers(Users.builder()
                .userId(UserThreadLocal.getUid())
                .friendId(Convert.toLong(userId))
                .date(System.currentTimeMillis())
                .build());

        appUsersService.addUsers(Users.builder()
                .userId(Convert.toLong(userId))
                .friendId(UserThreadLocal.getUid())
                .date(System.currentTimeMillis())
                .build());
    }

    public PageResult findContacts(Integer page, Integer pageSize, String keyword) {
        List<Users> usersList = appUsersService.findUsersList(UserThreadLocal.getUid());
        List<Long> friendIds = CollUtil.getFieldValues(usersList, "friendId", Long.class);
        Page<UserInfoEntity> pageUserInfo;
        if (StrUtil.isEmpty(keyword)) {
            pageUserInfo = appUserInfoService.pageUsers(page, pageSize, friendIds);
        } else {
            pageUserInfo = appUserInfoService.pageUsers(page, pageSize, friendIds, keyword);
        }

        List<UsersVo> vo = new ArrayList<>();
        List<UserInfoEntity> records = pageUserInfo.getRecords();
        for (UserInfoEntity entity : records) {
            UsersVo usersVo = new UsersVo();
            usersVo.setId(entity.getId());
            usersVo.setUserId(entity.getUserId().toString());
            usersVo.setAvatar(entity.getLogo());
            usersVo.setNickname(entity.getNickName());
            usersVo.setGender(entity.getSex() == 2 ? "man" : "woman");
            usersVo.setAge(entity.getAge());
            usersVo.setCity(entity.getCity());
            vo.add(usersVo);
        }

        return new PageResult(page, pageSize, pageUserInfo.getTotal(), vo);
    }

    public PageResult getComments(Integer page, Integer pageSize, int type) {
        Comment comment = Comment.builder()
                .publishUserId(UserThreadLocal.getUid())
                .commentType(type)
                .build();
        return appCommentService.getComments(comment, page, pageSize);
    }

    public PageResult getAnnouns(Integer page, Integer pageSize) {
        List<Announcement> all = announcementService.findAll();
        List<Announcement> list = CollUtil.sub(all, (page - 1) * pageSize, NumberUtil.min(page * pageSize, all.size()));
        List<AnnouncementVo> vo = new ArrayList<>();
        for (Announcement announ : list) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(announ.getId().toString());
            announcementVo.setTitle(announ.getTitle());
            announcementVo.setDescription(announ.getDescription());
            announcementVo.setCreateDate(DateUtil.format(announ.getCreated(), "yyyy-MM-dd HH:mm"));
            vo.add(announcementVo);
        }
        return new PageResult(page, pageSize, Convert.toLong(all.size()), vo);
    }
}
